package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.addressbook.manager.AddressBookCustomerFieldInfoManager;
import com.seeyon.apps.ext.bbnSSO.ssologin.util.JWTUtil;
import com.seeyon.apps.nygj.util.HttpKit;
import com.seeyon.apps.nygj.util.StrKit;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.formula.FormulaUtil;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.logging.Log;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Path("jssdk")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
public class CustomSSOResources extends BaseResource {

    private static final Log log = CtpLogFactory.getLog(CustomSSOResources.class);
    @Context
    private HttpServletRequest request;

    @Context
    private HttpServletResponse response;

    private static AddressBookCustomerFieldInfoManager addressBookCustomerFieldInfoManager = (AddressBookCustomerFieldInfoManager) AppContext.getBean("addressBookCustomerFieldInfoManager");

    /**
     * 获取单点登录认证码
     * 该方法用于通过HTTP GET请求获取单点登录（SSO）的认证码它主要经历了几个步骤：
     * 1. 从请求参数中提取认证码（authCode）。
     * 2. 若认证码非空，使用认证码向指定URL获取访问令牌（accessToken）。
     * 3. 使用获取的访问令牌获取用户信息，特别是用户的电话号码。
     * 4. 根据电话号码获取对应的系统登录名。
     * 5. 最后，使用登录名构造重定向URL，使用户能够完成单点登录流程。
     *
     * @param param 参数映射，目前未使用但保留以备将来扩展
     * @return 响应对象，可能包含错误信息或重定向到登录页面
     */
    @GET
    @Path("integration/sso/authCode")
    public Response acquireSSOAuthCode(Map<String, Object> param) {
        try {
            Long id = AppContext.getCurrentUser().getId();
            String appID = str(FormulaUtil.getVar("appID"));
            log.info("appID:" + appID);
            String keySecret = str(FormulaUtil.getVar("keySecret"));
            log.info("keySecret:" + keySecret);
            String timestamp = String.valueOf(System.currentTimeMillis());
            String zsjCode = addressBookCustomerFieldInfoManager.getByMemberId(id).getExtAttr4();
            log.info("一体化人员编码:" + zsjCode);
            if (!"".equals(zsjCode)) {
                StringBuilder stb = new StringBuilder();
                stb.append("https://fip.cscec.com/OSPPortal/CSCPortal.jsp?");
                String str2 = keySecret + "appID" + appID + "timestamp" + timestamp + "user" + zsjCode + keySecret;
                String tokenStr = DigestUtils.md5DigestAsHex(str2.getBytes(StandardCharsets.UTF_8)).toUpperCase();
                stb.append("token=").append(tokenStr).append("&user=").append(zsjCode);
                stb.append("&appID=").append(appID).append("&timestamp=").append(timestamp);
                String url = stb.toString();
                log.info("一体化单点登录url地址:" + url);
                response.sendRedirect(url);
            }
        } catch (Exception e) {
            log.error("单点登录接口异常信息:", e);
        }
        return null;
    }

    @GET
    @Path("real/estate/calculations/sso/authCode")
    public Response RealEstateCalculationsSSOAuthCode(Map<String, Object> param) {
        try {
            User user = AppContext.getCurrentUser();
            String loginName = user.getLoginName();
            log.info("获取当前用户信息:" + loginName);
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("username", loginName);

            HashMap<String, Object> clientInfo = new HashMap<String, Object>();
            String client_id = StrKit.str(FormulaUtil.getVar("client_id"));
            clientInfo.put("client_id", client_id);
            clientInfo.put("username", loginName);
            log.info("clientInfo:" + clientInfo);
            String token = JWTUtil.createTokenJWT(clientInfo);
            log.info("----> login token:" + token);
            Map<String, Object> map = new HashMap<>();
            String url = StrKit.str(FormulaUtil.getVar("dwp_code_url"));
            String redirect = url + token;
            log.info("redirect" + redirect);
            String result = HttpKit.get(redirect, map);
            log.info("调用dwp系统免登录获取code接口返回信息:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msg = (String) jsonObject.get("msg");
            String code = (String) jsonObject.get("code");
            if (msg.equals("success")) {
                String real_estate_calculations_url = StrKit.str(FormulaUtil.getVar("real_estate_calculations_url"));
                String real_estate_calculations_url_new = real_estate_calculations_url + "?code=" + code;
                log.info("地产测算跳转地址地址:" + real_estate_calculations_url_new);
                response.sendRedirect(real_estate_calculations_url_new);
            }
        } catch (Exception e) {
            log.error("地产测算单点登录接口异常信息:", e);
        }
        return null;
    }

    public static String str(Object o) {
        // 判断对象是否为null
        if (o == null) {
            return "";
        }
        // 判断对象是否已经是字符串类型
        if (o instanceof String) {
            return (String) o;
        }
        // 对象不是null且不是字符串类型，调用toString方法转换
        return o.toString();
    }
}